// 好友分组状态管理
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { friendGroupService } from '@/services'
import type { 
  FriendGroup, 
  CreateFriendGroupRequest,
  UpdateFriendGroupRequest 
} from '@/types'

export const useFriendGroupsStore = defineStore('friendGroups', () => {
  // 状态
  const groups = ref<FriendGroup[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  
  // 计算属性
  const sortedGroups = computed(() => 
    [...groups.value].sort((a, b) => a.sortOrder - b.sortOrder)
  )
  
  const defaultGroup = computed(() => 
    groups.value.find(group => group.isDefault)
  )
  
  const customGroups = computed(() => 
    groups.value.filter(group => !group.isSystem)
  )
  
  const totalFriendCount = computed(() => 
    groups.value.reduce((total, group) => total + (group.friendCount || 0), 0)
  )
  
  // 操作方法
  
  /**
   * 创建好友分组
   */
  async function createGroup(request: CreateFriendGroupRequest): Promise<FriendGroup> {
    try {
      isLoading.value = true
      error.value = null
      
      const group = await friendGroupService.createGroup(request)
      groups.value.push(group)
      
      return group
    } catch (err) {
      error.value = err instanceof Error ? err.message : '创建好友分组失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 更新好友分组
   */
  async function updateGroup(groupId: number, request: UpdateFriendGroupRequest): Promise<FriendGroup> {
    try {
      isLoading.value = true
      error.value = null
      
      const updatedGroup = await friendGroupService.updateGroup(groupId, request)
      
      // 更新本地状态
      const index = groups.value.findIndex(group => group.id === groupId)
      if (index !== -1) {
        groups.value[index] = updatedGroup
      }
      
      return updatedGroup
    } catch (err) {
      error.value = err instanceof Error ? err.message : '更新好友分组失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 删除好友分组
   */
  async function deleteGroup(groupId: number, userId: number): Promise<void> {
    try {
      isLoading.value = true
      error.value = null
      
      await friendGroupService.deleteGroup(groupId, userId)
      
      // 从本地状态中移除
      const index = groups.value.findIndex(group => group.id === groupId)
      if (index !== -1) {
        groups.value.splice(index, 1)
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '删除好友分组失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 加载用户的所有分组
   */
  async function loadUserGroups(userId: number, refresh = false): Promise<void> {
    try {
      if (refresh || groups.value.length === 0) {
        isLoading.value = true
        error.value = null
      }
      
      const userGroups = await friendGroupService.getUserGroupsWithCount(userId)
      groups.value = userGroups
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载好友分组失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 调整分组排序
   */
  async function reorderGroups(userId: number, groupIds: number[]): Promise<void> {
    try {
      isLoading.value = true
      error.value = null
      
      await friendGroupService.reorderGroups({ userId, groupIds })
      
      // 更新本地排序
      groupIds.forEach((groupId, index) => {
        const group = groups.value.find(g => g.id === groupId)
        if (group) {
          group.sortOrder = index + 1
        }
      })
    } catch (err) {
      error.value = err instanceof Error ? err.message : '调整分组排序失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 移动好友到分组
   */
  async function moveFriendToGroup(userId: number, friendId: number, groupId?: number): Promise<void> {
    try {
      isLoading.value = true
      error.value = null
      
      await friendGroupService.moveFriendToGroup({ userId, friendId, groupId })
      
      // 更新分组的好友数量
      await refreshGroupCounts(userId)
    } catch (err) {
      error.value = err instanceof Error ? err.message : '移动好友到分组失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 批量移动好友到分组
   */
  async function moveFriendsToGroup(userId: number, friendIds: number[], groupId?: number): Promise<void> {
    try {
      isLoading.value = true
      error.value = null
      
      await friendGroupService.moveFriendsToGroup({ userId, friendIds, groupId })
      
      // 更新分组的好友数量
      await refreshGroupCounts(userId)
    } catch (err) {
      error.value = err instanceof Error ? err.message : '批量移动好友到分组失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 刷新分组的好友数量
   */
  async function refreshGroupCounts(userId: number): Promise<void> {
    try {
      const promises = groups.value.map(async (group) => {
        try {
          const count = await friendGroupService.getFriendCountInGroup(group.id, userId)
          group.friendCount = count
        } catch (error) {
          console.error(`Failed to refresh count for group ${group.id}:`, error)
        }
      })
      
      await Promise.allSettled(promises)
    } catch (err) {
      console.error('刷新分组好友数量失败:', err)
    }
  }
  
  /**
   * 获取或创建默认分组
   */
  async function getOrCreateDefaultGroup(userId: number): Promise<FriendGroup> {
    let defaultGrp = defaultGroup.value
    
    if (!defaultGrp) {
      try {
        defaultGrp = await friendGroupService.createDefaultGroup(userId)
        groups.value.push(defaultGrp)
      } catch (err) {
        error.value = err instanceof Error ? err.message : '创建默认分组失败'
        throw err
      }
    }
    
    return defaultGrp
  }
  
  /**
   * 检查分组名称是否可用
   */
  async function isGroupNameAvailable(userId: number, name: string, excludeGroupId?: number): Promise<boolean> {
    try {
      return await friendGroupService.isGroupNameAvailable(userId, name, excludeGroupId)
    } catch (err) {
      console.error('检查分组名称可用性失败:', err)
      return false
    }
  }
  
  /**
   * 批量创建分组
   */
  async function batchCreateGroups(userId: number, groupNames: string[]): Promise<{
    success: FriendGroup[]
    failed: string[]
    errors: string[]
  }> {
    try {
      isLoading.value = true
      error.value = null
      
      const result = await friendGroupService.batchCreateGroups(userId, groupNames)
      
      // 添加成功创建的分组到本地状态
      groups.value.push(...result.success)
      
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '批量创建分组失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 根据ID获取分组
   */
  function getGroupById(groupId: number): FriendGroup | undefined {
    return groups.value.find(group => group.id === groupId)
  }
  
  /**
   * 根据名称获取分组
   */
  function getGroupByName(name: string): FriendGroup | undefined {
    return groups.value.find(group => group.name === name)
  }
  
  /**
   * 获取分组统计信息
   */
  const groupStats = computed(() => ({
    total: groups.value.length,
    custom: customGroups.value.length,
    system: groups.value.filter(g => g.isSystem).length,
    totalFriends: totalFriendCount.value,
    averageFriendsPerGroup: groups.value.length > 0 ? Math.round(totalFriendCount.value / groups.value.length) : 0
  }))
  
  /**
   * 清除错误状态
   */
  function clearError(): void {
    error.value = null
  }
  
  /**
   * 重置状态
   */
  function reset(): void {
    groups.value = []
    isLoading.value = false
    error.value = null
  }
  
  return {
    // 状态
    groups,
    isLoading,
    error,
    
    // 计算属性
    sortedGroups,
    defaultGroup,
    customGroups,
    totalFriendCount,
    groupStats,
    
    // 方法
    createGroup,
    updateGroup,
    deleteGroup,
    loadUserGroups,
    reorderGroups,
    moveFriendToGroup,
    moveFriendsToGroup,
    refreshGroupCounts,
    getOrCreateDefaultGroup,
    isGroupNameAvailable,
    batchCreateGroups,
    getGroupById,
    getGroupByName,
    clearError,
    reset
  }
})